package com.sanri.tools.modules.mock.l7.websocket.chat.service;

import com.sanri.tools.modules.core.security.entitys.UserProfile;
import com.sanri.tools.modules.mock.l7.websocket.chat.repository.ChatUserRepository;
import com.sanri.tools.modules.mock.l7.websocket.chat.repository.ChatGroupRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class ChatGroupService {
    @Autowired
    private ChatGroupRepository chatGroupRepository;
    @Autowired
    private ChatUserRepository chatUserRepository;

    public void createGroup(UserProfile userProfile, String admin) throws IOException {
        chatGroupRepository.createGroup(userProfile, admin);

        chatUserRepository.joinGroup(admin, userProfile.getUsername());
    }

    public void removeGroup(String groupName){
        // 检测是否为管理员操作
        // todo

        List<String> groupUsers = chatGroupRepository.groupUsers(groupName);

        // 每个用户先退出组
        for (String groupUser : groupUsers) {
            chatUserRepository.leaveGroup(groupUser, groupName);
        }

        // 删除组
        chatGroupRepository.removeGroup(groupName);
    }

    public UserProfile profile(String groupName) throws IOException {
        return chatGroupRepository.profile(groupName);
    }

    public List<String> users(String groupName){
        return chatGroupRepository.groupUsers(groupName);
    }

    public void addUser(String groupName, String username) throws IOException {
        chatGroupRepository.addUser(groupName, username);

        chatUserRepository.joinGroup(username, groupName);
    }

    public void removeUser(String groupName, String username) throws IOException {
        chatGroupRepository.removeUser(groupName, username);

        chatUserRepository.leaveGroup(username, groupName);
    }

}
